<template>
  <uni-popup ref="popup" type="bottom">
    <view class="spec-popup">
      <!-- 商品信息区 -->
      <view class="goods-info">
        <image :src="goodsInfo.images?.[0]" mode="aspectFill" class="thumb" />
        <view class="info">
          <text class="price"
            >¥{{ displayPrice }}</text
          >
          <text class="selected"
            >已选：{{ selectedSpecText || "请选择规格" }}</text
          >
        </view>
        <view class="close" @tap="close">
          <uni-icons type="closeempty" size="24" color="#999" />
        </view>
      </view>

      <!-- 规格选择区 -->
      <scroll-view scroll-y class="specs-wrap">
        <view
          class="spec-group"
          v-for="(group, groupIndex) in goodsInfo.specs"
          :key="groupIndex"
        >
          <text class="title">{{ group.name }}</text>
          <view class="options">
            <text
              v-for="(item, index) in group.values"
              :key="index"
              :class="[
                'option',
                { active: selectedSpecs[groupIndex] === index },
              ]"
              @tap="selectSpec(groupIndex, index)"
              >{{ item.valueName }}</text
            >
          </view>
        </view>

        <!-- 数量选择 -->
        <view class="quantity-wrap">
          <text class="title">数量</text>
          <uni-number-box
            v-model="quantity"
            :min="1"
            :max="selectedSku?.stock || 99"
          />
        </view>
      </scroll-view>

      <!-- 确认按钮 -->
      <button class="confirm-btn" :disabled="!isSpecSelected" @tap="confirm">
        确定
      </button>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, computed } from "vue";

const props = defineProps({
  goodsInfo: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["update:modelValue", "confirm"]);

// 响应式数据
const popup = ref(null);
const selectedSpecs = ref([]);
const quantity = ref(1);
const maxQuantity = ref(99);

// 添加一个工具函数来标准化规格值组合
const normalizeSpecValues = (specs) => {
  // 按规格名称排序，确保顺序一致
  return specs
    .sort((a, b) => a.name.localeCompare(b.name))
    .map(spec => spec.value)
    .join(';');
};

// 修改价格显示计算属性
const displayPrice = computed(() => {
  if (selectedSpecs.value.length > 0) {
    const selectedValues = props.goodsInfo.specs
      .map((spec, index) => {
        const valueIndex = selectedSpecs.value[index];
        if (valueIndex === -1) return null;
        return {
          name: spec.name,
          value: `${spec.name}:${spec.values[valueIndex].valueName}`
        };
      })
      .filter(Boolean);

    const normalizedValues = normalizeSpecValues(selectedValues);

    const matchedSku = props.goodsInfo.skus?.find(
      (sku) => {
        const skuSpecs = sku.specValues.split(';').map(spec => {
          const [name, value] = spec.split(':');
          return { name, value: `${name}:${value}` };
        });
        return normalizeSpecValues(skuSpecs) === normalizedValues;
      }
    );

    if (matchedSku) {
      return matchedSku.salePrice;
    }
  }

  return props.goodsInfo.salePrice;
});

// 计算属性
const selectedSpecText = computed(() => {
  if (!selectedSpecs.value.length) return "";
  return props.goodsInfo.specs
    ?.map((group, index) => {
      const selectedIndex = selectedSpecs.value[index];
      if (selectedIndex === -1) return '';
      return group.values[selectedIndex]?.valueName;
    })
    .filter(Boolean)
    .join("，");
});

const isSpecSelected = computed(() => {
  if (!props.goodsInfo.specs?.length) return true;
  return (
    selectedSpecs.value.length === props.goodsInfo.specs.length &&
    selectedSpecs.value.every((index) => index !== -1)
  );
});

// 获取选中的SKU
const selectedSku = computed(() => {
  if (!isSpecSelected.value) return null;

  // 获取选中的规格值组合
  const selectedValues = props.goodsInfo.specs
    .map((spec, index) => {
      const valueIndex = selectedSpecs.value[index];
      if (valueIndex === -1) return null;
      return {
        name: spec.name,
        value: `${spec.name}:${spec.values[valueIndex].valueName}`
      };
    })
    .filter(Boolean);

    const normalizedValues = normalizeSpecValues(selectedValues);

  return props.goodsInfo.skus?.find(
    (sku) => {
      const skuSpecs = sku.specValues.split(';').map(spec => {
        const [name, value] = spec.split(':');
        return { name, value: `${name}:${value}` };
      });
      return normalizeSpecValues(skuSpecs) === normalizedValues;
    }
  );
});

// 修改当前SKU的计算属性
const currentSku = computed(() => {
  if (!selectedSpecs.value.length) return null;

  const selectedValues = props.goodsInfo.specs
    .map((spec, index) => {
      const valueIndex = selectedSpecs.value[index];
      if (valueIndex === -1) return null;
      return {
        name: spec.name,
        value: `${spec.name}:${spec.values[valueIndex].valueName}`
      };
    })
    .filter(Boolean);

    const normalizedValues = normalizeSpecValues(selectedValues);

  return props.goodsInfo.skus?.find(
    (sku) => {
      const skuSpecs = sku.specValues.split(';').map(spec => {
        const [name, value] = spec.split(':');
        return { name, value: `${name}:${value}` };
      });
      return normalizeSpecValues(skuSpecs) === normalizedValues;
    }
  );
});

// 确认选择
const confirm = () => {
  if (!isSpecSelected.value) {
    uni.showToast({
      title: "请选择完整规格",
      icon: "none",
    });
    return;
  }

  const sku = selectedSku.value;

  if (!sku) {
    uni.showToast({
      title: "所选规格无效",
      icon: "none",
    });
    return;
  }

  // 检查库存
  if (sku.stock < quantity.value) {
    uni.showToast({
      title: "库存不足",
      icon: "none",
    });
    return;
  }

  emit("confirm", {
    sku: {
      id: sku.skuId,
      salePrice: sku.salePrice,
      linePrice: sku.linePrice,
      stock: sku.stock,
      code: sku.code,
      specs: sku.specValues,
    },
    quantity: quantity.value,
    specs: selectedSpecs.value,
  });
  close();
};

// 选择规格
const selectSpec = (groupIndex, valueIndex) => {
  // 确保 selectedSpecs 数组已初始化
  if (!selectedSpecs.value.length) {
    selectedSpecs.value = new Array(props.goodsInfo.specs?.length || 0).fill(
      -1
    );
  }

  // 更新选中状态
  selectedSpecs.value[groupIndex] = valueIndex;

  const sku = currentSku.value;

  if (sku) {
    // 更新最大可选数量
    maxQuantity.value = sku.stock;
    // 如果当前选择数量超过库存，调整数量
    if (quantity.value > sku.stock) {
      quantity.value = sku.stock;
    }
  }
};

// 打开弹窗时重置状态
const open = () => {
  popup.value.open();
  // 重置选择状态
  selectedSpecs.value = new Array(props.goodsInfo.specs?.length || 0).fill(-1);
  quantity.value = 1;
  maxQuantity.value = props.goodsInfo.skus?.[0]?.stock || 99;
};

const close = () => {
  popup.value.close();
};

// 对外暴露方法
defineExpose({
  open,
  close,
});
</script>

<style lang="scss">
.spec-popup {
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 99999;

  // 商品息区
  .goods-info {
    display: flex;
    padding: 30rpx;
    border-bottom: 1rpx solid #eee;

    .thumb {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
    }

    .info {
      flex: 1;
      padding: 0 20rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .price {
        font-size: 36rpx;
        color: #ff4444;
        font-weight: bold;
      }

      .selected {
        font-size: 26rpx;
        color: #666;
      }
    }

    .close {
      padding: 10rpx;
    }
  }

  // 规格选择区
  .specs-wrap {
    max-height: 60vh;
    padding: 20rpx 30rpx;

    .spec-group {
      margin-bottom: 30rpx;

      .title {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 20rpx;
        display: block;
      }

      .options {
        display: flex;
        flex-wrap: wrap;

        .option {
          height: 60rpx;
          padding: 0 30rpx;
          line-height: 60rpx;
          border-radius: 4rpx;
          background-color: #f5f5f5;
          font-size: 26rpx;
          color: #333;
          margin: 0 20rpx 20rpx 0;

          &.active {
            background-color: #fff0f0;
            color: #ff4444;
            border: 1rpx solid #ff4444;
          }
        }
      }
    }

    .quantity-wrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;

      .title {
        font-size: 28rpx;
        color: #333;
      }
    }
  }

  // 确认按钮
  .confirm-btn {
    width: 100%;
    height: 100rpx;
    line-height: 100rpx;
    background-color: #ff4444;
    color: #fff;
    font-size: 32rpx;
    border-radius: 0;
    margin: 0;
    margin-bottom: 50rpx;
    padding: 0;

    &::after {
      display: none;
    }

    &[disabled] {
      background-color: #ccc;
    }
  }
}

// 弹窗样式覆盖
:deep(.uni-popup) {
  z-index: 99999 !important;
}

:deep(.uni-popup__mask) {
  z-index: 99998 !important;
  background-color: rgba(0, 0, 0, 0.6) !important;
}

:deep(.uni-popup__wrapper) {
  z-index: 99999 !important;
  position: fixed !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
}
</style>
